import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 可以在这里添加token等认证信息
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    
    // 如果后端返回的是标准格式 { code: 200, message: 'success', data: {} }
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === 200) {
        return data.data
      } else {
        ElMessage.error(data.message || '请求失败')
        return Promise.reject(new Error(data.message || '请求失败'))
      }
    }
    
    return data
  },
  (error) => {
    let message = '网络错误'
    
    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 400:
          message = data?.message || '请求参数错误'
          break
        case 401:
          message = '未授权，请重新登录'
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求地址不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = data?.message || `请求失败: ${status}`
      }
    } else if (error.request) {
      message = '网络连接失败'
    } else {
      message = error.message || '请求配置错误'
    }
    
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

// 设备模板相关API
export const deviceTemplateApi = {
  // 上传设备模板
  upload: (file: File, doClear: boolean=true, description?: string  ) => {
    const formData = new FormData()
    formData.append('file', file)
    if (description) {
      formData.append('description', description)
    }
    formData.append('doClear',doClear.toString())
    return api.post('/device/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取设备列表
  getDevices: (params?: any) => {
    return api.get('/device/list', { params })
  },

  // 获取设备模板导入记录
  getImportRecords: (params?: any) => {
    return api.get('/device/import-records', { params })
  },

  // 根据导入ID获取导入结果
  getImportResult: (importId: number) => {
    return api.get(`/device/import/${importId}`)
  },

  // 获取受令单位列表
  getCommandingUnits: () => {
    return api.get('/device/commanding-units')
  }
}


// 启动方案相关API
export const startupPlanApi = {
  // 上传启动方案并校验
  upload: (file: File, description?: string) => {
    const formData = new FormData()
    formData.append('file', file)
    if (description) {
      formData.append('description', description)
    }
    return api.post('/startup-plan/validate', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取校验结果
  getResults: (documentId: number) => {
    return api.get(`/startup-plan/result/${documentId}`)
  },

  // 获取启动方案列表
  getList: (params?: any) => {
    return api.get('/startup-plan/list', { params })
  },

  // 下载校验结果 
  download: (documentId: number, format: string = 'excel') => {
    return api.get(`/startup-plan/download/${documentId}`, {
      params: { format },
      responseType: 'blob'
    })
  }
}

// 术语库相关API
export const terminologyApi = {
  // 导入术语库文件
  import: (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/terminology/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 刷新术语缓存
  refreshCache: () => {
    return api.post('/terminology/refresh-cache')
  },

  // 获取二次设备术语
  getSecondaryTerms: () => {
    return api.get('/terminology/secondary')
  },

  // 获取一次设备术语
  getPrimaryTerms: () => {
    return api.get('/terminology/primary')
  },

  // 获取一次设备术语层级结构
  getPrimaryTermsHierarchy: () => {
    return api.get('/terminology/primary/hierarchy')
  },

  // 获取设备类型列表
  getDeviceTypes: () => {
    return api.get('/terminology/primary/device-types')
  },

  // 获取指定设备类型的编写原则
  getPrinciplesByParentId: (parentId: number) => {
    return api.get(`/terminology/primary/principles/${parentId}`)
  },

  // 获取标记删除的一次设备术语
  getDeletedPrimaryTerms: () => {
    return api.get('/terminology/primary/deleted')
  },

  // 保存二次设备术语
  saveSecondaryTerm: (term: any) => {
    return api.post('/terminology/secondary', term)
  },

    // 测试二次设备术语（原则）
  testSecondaryTerm: (term: any) => {
    return api.post('/terminology/secondary/test', term)
  },

  // 保存一次设备术语（原则）
  savePrimaryTerm: (term: any) => {
    return api.post('/terminology/primary', term)
  },

   // 测试一次设备术语（原则）
  testPrimaryTerm: (term: any) => {
    return api.post('/terminology/primary/test', term)
  },

  // 删除二次设备术语
  deleteSecondaryTerm: (id: string) => {
    return api.delete(`/terminology/secondary/${id}`)
  },

  // 删除一次设备术语
  deletePrimaryTerm: (id: string) => {
    return api.delete(`/terminology/primary/${id}`)
  },

  // 获取设备状态列表
  getDeviceStates: () => {
    return api.get('/terminology/device/states')
  },
    // 新增并重获取设备状态列表
  addDeviceState: (stateName:string) => {
    const formData = new FormData()
    formData.append('stateName', stateName)
    return api.post('/terminology/device/addAndRefresh', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  // 删除并重获取设备状态列表
  deleteDeviceState: (stateName:string) => {
    const formData = new FormData()
    formData.append('stateName', stateName)
    return api.post('/terminology/device/deleteAndRefresh', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
}

// 系统相关API
export const systemApi = {
  // 获取系统状态
  getStatus: () => {
    return api.get('/system/status')
  },

  // 获取系统健康状态
  getHealth: () => {
    return api.get('/system/health')
  },

  // 获取统计信息
  getStats: () => {
    return api.get('/system/stats')
  }
}

export default api